//清除所有cookie
export function clearAllCookie() {
    const keys = document.cookie.match(/[^ =;]+(?==)/g)
    const d = new Date()
    d.setTime(-1)
    if (keys) {
        let i = keys.length
        while (i >= 0) {
            document.cookie = `${ keys[i] }=0;expires=${ d.toUTCString() }`
            i -= 1
        }
    }
}

//获取cookie
export function getCookie(key : string) : string | undefined {
    const name = `${ key }=`
    const ca = document.cookie.split(';')
    for (let i = 0; i < ca.length; i += 1) {
        let c = ca[i]
        while (c.charAt(0) === ' ') c = c.substring(1)
        if (c.indexOf(name) !== -1) {
            return c.substring(name.length, c.length)
        }
    }
}

//获取cookie 并转换为对象
export function getCookieToObject<T extends Object>(key : string) : T | undefined {
    const val = getCookie(key)
    if (val) return JSON.parse(val)
}

//删除指定cookie
export function removeCookie(key : string) {
    const d = new Date()
    d.setTime(-1)
    const expires = `expires=${ d.toUTCString() };path=/`
    document.cookie = `${ key }=''; ${ expires }`
}

//判断是否有指定cookie
export function hasCookie(key : string) : boolean {
    return new RegExp(`(?:^|;\\s*)${ key }\\s*\\=`).test(document.cookie)
}

//设置cookie 将对象序列化值存入
export function setCookieFromObject(key : string, value : object, keepDays = 720) {
    setCookie(key, JSON.stringify(value), keepDays)
}

//设置cookie
export function setCookie(key : string, value : string, keepDays = 720) {
    const d = new Date()
    d.setTime(d.getTime() + keepDays * 24 * 60 * 60 * 1000)
    const expires = `expires=${ d.toUTCString() }`
    document.cookie = `${ key }=${ value }; ${ expires }`
}
